import os
import zipfile

import cv2
import numpy as np
from rasterio.io import MemoryFile
import matplotlib.pyplot as plt
from PIL import Image, ImageColor

def read_land_cover():
    parent_directory = 'E:\\map data'
    file = 'GLC_FCS30_2020.zip'
    keys_and_color = {}

    all_width = 21600; all_height = 10800
    all_image = np.zeros((all_height, all_width), dtype=np.uint8)

    local_width = -1; local_height = -1
    lon_size = 360; lat_size = 180

    directory_name = os.path.join(parent_directory, file)
    zip_file_info = zipfile.ZipFile(directory_name, 'r')
    file_list = zip_file_info.namelist()

    file_list_filtered = [s for s in file_list if s.endswith('.tif')]
    f_count = 0

    for file in file_list:
        if file.endswith('.tif'):
            print(f'{file} {f_count}/{len(file_list_filtered)}')
            single_file = zip_file_info.open(file)
            content = single_file.read()
            with MemoryFile(content) as memfile:
                # 打开内存文件中的 TIFF 数据集
                with memfile.open() as dataset:
                    # 示例：读取影像数据（numpy 数组）
                    image_nparray_0 = dataset.read()  # shape: (波段数, 高度, 宽度)

                    bounds = dataset.bounds
                    right = bounds.right; left = bounds.left
                    bottom = bounds.bottom; top = bounds.top

                    left_round = round(left); top_round = round(top)
                    width_gap = right - left; height_gap = bottom - top
                    width_gap_abs = abs(width_gap); height_gap_abs = abs(height_gap)

                    width_gap_round = round(width_gap); height_gap_round = round(-height_gap)
                    pixel_width = round(all_width * width_gap_abs / lon_size)
                    pixel_height = round(all_height * height_gap_abs / lat_size)

                    left_ratio = (left - (-180)) / (180 - (-180))
                    top_ratio = 1 - (top - (-90)) / (90 - (-90))

                    left_ratio_start = round(left_ratio * all_width)
                    top_ratio_start = round(top_ratio * all_height)

                    if left_ratio_start + pixel_width > all_width:
                        pixel_width = all_width - left_ratio_start

                    if top_ratio_start + pixel_height > all_height:
                        pixel_height = all_height - top_ratio_start

                    resized_image_cv2 = cv2.resize(image_nparray_0[0], (pixel_width, pixel_height),
                                                     interpolation=cv2.INTER_AREA)

                    all_image[top_ratio_start:top_ratio_start + pixel_height, left_ratio_start:left_ratio_start + pixel_width] = resized_image_cv2

                    t = 11

            f_count += 1

    zip_file_info.close()

    image = Image.fromarray(all_image)
    image.show()


    plt.imshow(all_image)
    plt.show()
    return 0

if __name__ == '__main__':
    read_land_cover()